<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 重写 Config_Database_Reader 类
 *
 * @author  Yellow.Chow <aultoale@gmail.com>
 * @version $Id: reader.php 1 2014-01-13 15:05:51Z zhouyl $
 * @license http://www.gnu.org/licenses/gpl-3.0.html    GPL 3
 */

/**
 * Database reader for the kohana config system
 *
 * @package    Kohana/Database
 * @category   Configuration
 * @author     Kohana Team
 * @copyright  (c) 2011 Kohana Team
 * @license    http://kohanaframework.org/license
 */
class Config_Database_Reader implements Kohana_Config_Reader
{

    protected $_db = 'default';

    protected $_table = 'config';

    protected $_data = NULL;

    protected $_cache_id = '__db_config';

    /**
     * Constructs the database reader object
     *
     * @param array Configuration for the reader
     */
    public function __construct(array $config = NULL)
    {
        if (isset($config['db']))
        {
            $this->_db = $config['db'];
        }

        if (isset($config['table']))
        {
            $this->_table = $config['table'];
        }
    }

    /**
     * Tries to load the specificed configuration group
     *
     * Returns FALSE if group does not exist or an array if it does
     *
     * @param  string $group Configuration group
     * @return boolean|array
     */
    public function load($group)
    {
        if ($group == 'database' OR $group == 'cache')
        {
            return FALSE;
        }

        if ($this->_data === NULL)
        {
            // 使用 Cache 进行缓存
            $this->_data = Cache::instance()->get($this->_cache_id);

            // 若无结果则执行回调函数并缓存结果
            if ( ! $this->_data)
            {
                $rows = DB::select('group_name', 'config_key', 'config_value')
                    ->from($this->_table)
                    ->fetch_all($this->_db);
                foreach ($rows as $row)
                {
                    $this->_data[$row['group_name']][$row['config_key']] = unserialize($row['config_value']);
                }

                Cache::instance()->set($this->_cache_id, $this->_data, 86400);
            }
        }

        return isset($this->_data[$group]) ? $this->_data[$group] : FALSE;
    }

}
